package com.chuangjiangx.member.stored.web.controller;

import com.chuangjiangx.commons.CurrentThreadContext;
import com.chuangjiangx.commons.exception.BaseException;
import com.chuangjiangx.commons.response.Response;
import com.chuangjiangx.commons.response.ResponseUtils;
import com.chuangjiangx.member.basic.web.controller.BaseController;
import com.chuangjiangx.member.basic.web.interceptor.Login;
import com.chuangjiangx.member.basic.web.response.CustomRechargeResponse;
import com.chuangjiangx.member.stored.web.response.StoredRulesListResponse;
import com.chuangjiangx.member.common.utils.BeanUtils;
import com.chuangjiangx.member.stored.ddd.query.MbrRechargeRuleQuery;
import com.chuangjiangx.member.stored.ddd.dal.dto.RechargeRuleList;
import com.chuangjiangx.member.stored.ddd.query.dto.CustomRechargeDTO;
import com.chuangjiangx.member.basic.ddd.domain.model.MbrUserContext;
import com.chuangjiangx.member.stored.ddd.domain.model.MbrGiftType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 储值规则列表
 */
@RestController
@RequestMapping(value = "/h5/recharge-rule", produces = "application/json")
public class RechargeRuleController extends BaseController {
    @Autowired
    private MbrRechargeRuleQuery mbrRechargeRuleQuery;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 储值规则列表
     *
     * @param request
     * @return com.chuangjiangx.commons.response.UnderlineResponse
     * @map storedRulesList List
     * @map page
     * @see StoredRulesListResponse
     */
    @RequestMapping(value = "/search-list")
    @ResponseBody
    @Login
    public Response searchStoredRulesList(HttpServletRequest request) {
        MbrUserContext memeberValue = (MbrUserContext) CurrentThreadContext.getCurrentUser();

        List<RechargeRuleList> storedRulesLists = mbrRechargeRuleQuery.queryRulesList(memeberValue.getMerchantId());

        //对象转换
        List<StoredRulesListResponse> responseList = storedRulesLists.stream()
                .map(o -> {
                    StoredRulesListResponse r = new StoredRulesListResponse();
                    org.springframework.beans.BeanUtils.copyProperties(o, r, "amount", "giftScore", "giftAmount");
                    r.setAmount(o.getAmount().stripTrailingZeros().toPlainString());
                    r.setGiftScore(o.getGiftScore() == null ? "" : o.getGiftScore().stripTrailingZeros().toPlainString());
                    r.setGiftAmount(o.getGiftAmount() == null ? "" : o.getGiftAmount().stripTrailingZeros().toPlainString());
                    return r;
                })
                .collect(Collectors.toList());
        //排序规则, 赠送金额最大的排前面
        Optional<StoredRulesListResponse> optional = responseList.stream()
                .filter(r -> r.getGiftType() == MbrGiftType.AMOUNT.value)
                .sorted(Comparator.comparing(r -> r.getGiftAmount(), Comparator.reverseOrder()))
                .findFirst();
        if(optional.isPresent()){
            StoredRulesListResponse maxRule = optional.get();
            responseList = responseList.stream()
                    .filter(o -> !Objects.equals(maxRule.getId(),o.getId()))
                    .collect(Collectors.toList());
            responseList.add(0,maxRule);
        }

        return ResponseUtils.success("storedRulesList", responseList);
    }

    /**
     * 查询自定义储值开关是否开启
     *
     * @return com.chuangjiangx.commons.response.UnderlineResponse
     * @see CustomRechargeResponse
     */
    @RequestMapping(value = "/check-rule-open")
    @ResponseBody
    @Login
    public Response checkRulesOpen(HttpServletRequest request) {
        MbrUserContext memeberValue = (MbrUserContext) CurrentThreadContext.getCurrentUser();
        CustomRechargeDTO dto = mbrRechargeRuleQuery.checkRulesOpen(memeberValue.getMerchantId());
        CustomRechargeResponse rulesOpenStatus = new CustomRechargeResponse();
        BeanUtils.convertBean(dto, rulesOpenStatus);
        return ResponseUtils.success(rulesOpenStatus);
    }

    /**
     * 查找储值赠送最大金额
     */
    @RequestMapping(value = "/gift-amount-max-name")
    @ResponseBody
    public Response getGiftAmountMax(HttpServletRequest request, @RequestParam(required = false,defaultValue = "0" ) Long merchantId) {
        MbrUserContext user = loginService.currentUserContext();
        Long mid = null;
        if(merchantId != 0L){
            mid = merchantId;
        }else if(null != user){
            mid = user.getMerchantId();
        }else{
            throw new BaseException("","未知商户?");
        }
        List<RechargeRuleList> ruleLists = mbrRechargeRuleQuery.queryRulesList(mid);
        Optional<RechargeRuleList> optional = ruleLists.stream()
                .filter(r -> r.getGiftType() == MbrGiftType.AMOUNT.value)
                .sorted(Comparator.comparing(r -> r.getGiftAmount(), Comparator.reverseOrder()))
                .findFirst();
        optional.ifPresent(o -> o.setName("充"+o.getAmount().stripTrailingZeros().toPlainString()+"元送"+o.getGiftAmount().stripTrailingZeros().toPlainString()+"元"));
        return ResponseUtils.success(optional.orElse(null));
    }
}
